package cn.i7baozh.nacos.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 1、类名必须叫做XxxGatewayFilterFactory.注入到Spring容器后使用时的名称就叫做Xxx。
 *
 * 2、类必须继承 AbstractGatewayFilterFactory，让父类帮实现配置参数的处理
 *
 * 3、所有需要传递进来的参数都配置到当前类的内部类Config中
 *
 * @author : baoqi.zhang
 * @date :   2022/4/22 22:09
 */
@Component
@Slf4j
public class MyTempGatewayFilterFactory extends AbstractGatewayFilterFactory<MyTempGatewayFilterFactory.CostTimeConfig> {

    public MyTempGatewayFilterFactory() {
        super(CostTimeConfig.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("name", "path");
    }

    @Override
    public GatewayFilter apply(CostTimeConfig config) {
        log.info("********"+config.toString());
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                String path = exchange.getRequest().getPath().toString();
                log.info("path:{}", path );
                //从PathVariable取数据
                Map<String, String> attribute = exchange.getAttribute(ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
                log.info("attribute:{}", attribute);
                return chain.filter(exchange);
            }
        };
    }

    /**
     * 配置类
     */
    public static class CostTimeConfig{

        private String name;

        private String path;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        @Override
        public String toString() {
            return "CostTimeConfig{" +
                    "name='" + name + '\'' +
                    ", path='" + path + '\'' +
                    '}';
        }
    }
}
